首先我們建立的UserData.kt
就是我們資料庫中每一筆資料的欄位
@Entity
data class UserData(
@PrimaryKey(autoGenerate = true) var uid: Int,
@ColumnInfo(name = "app_name") var name: String?,
@ColumnInfo(name = "account") var account: String?,
@ColumnInfo(name = "password") var password: String?
)
PrimaryKey 代表主鍵
剩下都是其它欄位
以及新增UserDao.kt
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
@Dao
interface UserDao {
@Query("SELECT * FROM users")
fun getAll(): List<UserData>
@Query("SELECT * FROM users WHERE uid IN (:userIds)")
fun loadAllByIds(userIds: IntArray): List<UserData>
@Query("SELECT * FROM users WHERE app_name LIKE :first AND " +
"account LIKE :last LIMIT 1")
fun findByName(first: String, last: String): UserData
@Insert
fun insertAll(vararg users: UserData)
@Delete
fun delete(user: UserData)
}
此interface主要是操作SQL語法
還有許多資料庫CRUD方法都寫在這
新增Appdatabase.kt
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [(UserData::class)], version = 1, exportSchema = false)
abstract class Appdatabase : RoomDatabase() {
companion object {
const val DATABASE_NAME = "123.db"
@Volatile private var instance: Appdatabase? = null
private val LOCK = Any()
operator fun invoke(context: Context)= instance ?: synchronized(LOCK){
instance ?: buildDatabase(context).also { instance = it}
}
private fun buildDatabase(context: Context) = Room.databaseBuilder(context,
Appdatabase::class.java, DATABASE_NAME).build()
}
abstract fun getNotesDao(): UserDao
}